import JJRequest from './JJRequest';
import JJUtil from '../util/JJUtil.js'

export default class JJService {
    static request(requestClass, identity, parameters, isEncryption, isSaveToDisk, networkSuccessCallBack, networkFailCallBack, cacheCallBack) {
        const RequestClass = requestClass;
        const request = new RequestClass(identity, parameters, isEncryption, isSaveToDisk);

        JJService.requestWithObject(request, networkSuccessCallBack, networkFailCallBack, cacheCallBack)
    }

    static requestWithObject(request, networkSuccessCallBack, networkFailCallBack, cacheCallBack) {
        if (request.isSaveToDisk) {
            const value = request.obtainCache()
            if (JJUtil.isNotNull(value) && JJUtil.isNotNull(cacheCallBack)) {
                cacheCallBack(value, { 'identity' : request.identity });
            }
        }

        request.start(networkSuccessCallBack, networkFailCallBack)
    }

    static saveCustomCacheObject(obj, identity, isForAllAccount = true, requestClass = JJRequest, parameters = {}) {
        const RequestClass = requestClass;
        const request = new RequestClass(identity, parameters, true, true);
        if (isForAllAccount) {
            request.sensitiveDataForSavedFileName = '';
        }

        request.saveObjectToCache(obj);
    }

    static removeCustomCacheObject(identity, isForAllAccount = true, requestClass = JJRequest, parameters = {}) {
        const RequestClass = requestClass;
        const request = new RequestClass(identity, parameters, true, true);
        if (isForAllAccount) {
            request.sensitiveDataForSavedFileName = '';
        }
        request.removeCache();
    }

    static customCacheObject(identity, isForAllAccount = true, requestClass = JJRequest, parameters = {}) {
        const request = new requestClass(identity, parameters, true, true);
        if (isForAllAccount) {
            request.sensitiveDataForSavedFileName = '';
        }

        return request.obtainCache();
    }
}
